import 'dart:ffi';

import 'package:dear_lottery/tools/DL_Config.dart';
import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart';

import '../request/DL_DioRequest.dart';
import 'DL_LottoModel.dart';

class DL_DataViewModel {
  // 单例
  factory DL_DataViewModel() => _getInstance()!;
  static DL_DataViewModel get instance => _getInstance()!;
  static DL_DataViewModel? _instance;
  DL_DataViewModel._internal();
  static DL_DataViewModel? _getInstance() {
    _instance ??= DL_DataViewModel._internal();
    return _instance;
  }

  ///下一期数据模型
  late var nextDrawnModel = DL_NextDrawModel();

  late var allDatas = []; //全部json数据

  late var DL_lottoResultsData = []; //全部结果数据集合

  late var DL_resultsModels = []; //全部结果模型数组
  var DL_onePM_resultsModels = [];
  var DL_sixPM_resultsModels = [];
  var DL_eightPM_resultsModels = [];
  var DL_others_resultsModels = [];

  late var DL_DigitsDatas = []; //号码分区
  late var DL_CalculateTitles = []; //
  late var DL_AnalyticsRowResults = []; //走势图数据
  late var DL_CalculatedDrawings = []; //号码中奖次数
  late var DL_AverageSkipping = []; //平均遗漏
  late var DL_MaximumSkipping = []; //最大遗漏→
  late var DL_MaximumConsecution = []; //最大连开→
  late var DL_ChooseNumbers = []; //待选号码

  late var DL_draws_date = []; //全部开奖日期
  late var DL_draws_date_1pm = []; //
  late var DL_draws_date_6pm = []; //
  late var DL_draws_date_8pm = []; //
  late var DL_draws_date_other = []; //

  late var DL_ticketNumbers_all = []; // 全部开奖号
  late var DL_ticketNumbers_1pm = []; //
  late var DL_ticketNumbers_6pm = []; //
  late var DL_ticketNumbers_8pm = []; //
  late var DL_ticketNumbers_other = []; //

//获取全部数据
  Future<bool> getData() async {
    try {
      // Your data fetching logic here
      // For example:
      var response = await DlDiorequest().requestAllData();
      debugPrint('$response');

      int status = response['status'];
      List data = response['data'];
      if (status == 200 && data.isNotEmpty) {
        DL_lottoResultsData = data;
        configAllDataModels(data);

        return true;
      }

      return false; // Return true if data fetching is successful
    } catch (e) {
      // Handle any errors
      return false; // Return false if there is an error
    }
  }

  //获取下一期
  Future<bool> getNextDrawnData() async {
    var response = await DlDiorequest().requestNextDrawData();
    debugPrint('$response');

    int status = response['status'];
    var data = response['data'];
    if (status == 200 && data.isNotEmpty) {
      nextDrawnModel = DL_NextDrawModel.fromJson(data);
      return true;
    }
    return false;
  }

  void configAllDataModels(List datas) {
    for (var data in datas) {
      var model = DL_LottoModel.fromJson(data);
      DL_resultsModels.add(model);
    }
    configDigitsData();
    lotteryType();
  }

  void lotteryType() {
    if (DL_resultsModels.isEmpty) {
      return;
    }
    for (DL_LottoModel model in DL_resultsModels) {
      //开奖日期
      DateTime drawDateTimeUTC = DateTime.parse(model.draw_date!);
      var dateTimeString = DateFormat('d/MMM/y').format(drawDateTimeUTC);
      List first_prize_num = model.first_prize_num ?? [];
      List<String> charArray = [];
      if (first_prize_num.isEmpty) {
        //空数据则跳过
        continue;
      }
      var firstPrizeNum = first_prize_num[0];
      charArray = firstPrizeNum.split('');
      if (charArray.length != 8) {
        //号码有问题也跳过
        continue;
      }
      DL_ticketNumbers_all.add(charArray);
      switch (model.lottery_type) {
        case '1PM':
          DL_ticketNumbers_1pm.add(charArray);
          DL_onePM_resultsModels.add(model);
          DL_draws_date_1pm.add(dateTimeString);
          break;
        case '6PM':
          DL_ticketNumbers_6pm.add(charArray);
          DL_sixPM_resultsModels.add(model);
          DL_draws_date_6pm.add(dateTimeString);
          break;
        case '8PM':
          DL_ticketNumbers_8pm.add(charArray);
          DL_eightPM_resultsModels.add(model);
          DL_draws_date_8pm.add(dateTimeString);
          break;
        case 'Others':
          DL_ticketNumbers_other.add(charArray);
          DL_others_resultsModels.add(model);
          DL_draws_date_other.add(dateTimeString);
          break;
        default:
      }
    }
    DL_getAnalyticsResults(0);
    debugPrint('');
  }

  getCalculateTitle() {
    var titles = [
      'Drawn\nCount',
      'Average\nSkipping',
      'Maximum\nSkipping',
      'Maximum\nConsecution',
      'Choose &\nSave Ticket',
    ];
    DL_CalculateTitles = titles;
    return titles;
  }

  ///全部分区头部
  configDigitsData() {
    for (var i = 0; i < DL_Config.digitsStringArr.length; i++) {
      if (i == 0) {
        DL_DigitsDatas.add(DL_Config.FirstNumDigits);
      } else if (i == 1) {
        DL_DigitsDatas.add(DL_Config.otherDigitNums);
      } else if (i == 2) {
        DL_DigitsDatas.add(DL_Config.DigitLetters);
      } else {
        DL_DigitsDatas.add(DL_Config.otherDigitNums);
      }
    }
  }

  ///获取每个分类的日期数据
  getPMTypeDrawnDate(int index) {
    List results = [];
    List calculateTitles = getCalculateTitle();

    switch (index) {
      case 0:
        results = DL_draws_date_1pm;
        break;
      case 1:
        results = DL_draws_date_6pm;
        break;
      case 2:
        results = DL_draws_date_8pm;
        break;
      case 3:
        results = DL_draws_date_other;
        break;

      default:
    }

    if (results.isNotEmpty) {
      return results.reversed.toList() + calculateTitles;
    }

    return results;
  }

  ///
  //匹配Analytics每一行开奖结果
  DL_getAnalyticsResults(int typeIndex) async {
    DL_AnalyticsRowResults.clear();
    var winningNumbers = [];
    switch (typeIndex) {
      case 0:
        winningNumbers = DL_ticketNumbers_1pm;
        break;
      case 1:
        winningNumbers = DL_ticketNumbers_6pm;
        break;
      case 2:
        winningNumbers = DL_ticketNumbers_8pm;
        break;
      case 3:
        winningNumbers = DL_ticketNumbers_other;
        break;
    }

    ///遍历全部开奖结果，每一行
    var winningNumbersList = winningNumbers.reversed.toList();
    for (var i = 0; i < winningNumbersList.length; i++) {
      var results = [];
      List resultNumbers = winningNumbersList[i];

      if (resultNumbers.length != DL_DigitsDatas.length) {
        ///要保证长度相同
        break;
      }

      ///遍历每个中奖号码
      for (var k = 0; k < resultNumbers.length; k++) {
        var rNum = resultNumbers[k];
        List digitsData = DL_DigitsDatas[k];
        var codeArray = [];
        int jStr = i + 1;

        ///遍历每个区号码
        for (var j = 0; j < digitsData.length; j++) {
          Map element = digitsData[j];
          var dNum = element['code'];
          var rowCode = {'code': (jStr).toString(), 'isRight': false};
          if (i <= 0) {
            //第一行
            if (dNum == rNum) {
              rowCode = {'code': rNum, 'isRight': true};
            }
          } else {
            ///第二行，
            var lastRowResults = DL_AnalyticsRowResults[i - 1]; //取上一行数据
            Map lastRowMap = lastRowResults[k];
            List lastRowNums = lastRowMap['nums'];
            Map lastRowNumMap = lastRowNums[j];
            bool isRight = lastRowNumMap['isRight']; //上一行对应位置是否中奖号码
            var lastRowNum = lastRowNumMap['code'];
            if (isRight) {
              rowCode = {'code': (1).toString(), 'isRight': false};
            } else {
              rowCode = {
                'code': (int.parse(lastRowNum) + 1).toString(),
                'isRight': false
              };
            }

            ///查看开奖号码是否在当前分区
            if (dNum == rNum) {
              rowCode = {'code': dNum, 'isRight': true};
            }
          }

          codeArray.add(rowCode);
        }
        Map digitMap = {'title': '', 'nums': codeArray};
        results.add(digitMap);
      }

      DL_AnalyticsRowResults.add(results);
    }
    debugPrint('DL_AnalyticsRowResults---$DL_AnalyticsRowResults');
    DL_getCalculatedDrawings(0);
    DL_AnalyticsRowResults.add(DL_CalculatedDrawings);
    DL_AnalyticsRowResults.add(DL_AverageSkipping);
    DL_AnalyticsRowResults.add(DL_MaximumSkipping);
    DL_AnalyticsRowResults.add(DL_MaximumConsecution);
    DL_AnalyticsRowResults.add(DL_ChooseNumbers);
    return DL_AnalyticsRowResults;
  }

  ///每个号码开奖次数
  DL_getCalculatedDrawings(int typeIndex) {
    DL_CalculatedDrawings.clear();

    //1、遍历每个分区
    for (var p = 0; p < DL_DigitsDatas.length; p++) {
      List digitsData = DL_DigitsDatas[p];

      var codeCountArray = [];
      //2、遍历每个号码
      for (var j = 0; j < digitsData.length; j++) {
        Map digitMap = digitsData[j];
        String codeString = digitMap['code'];
        debugPrint('check---$codeString');
        int count = 0;
        //3、遍历每个号码的开奖次数
        for (var k = 0; k < DL_AnalyticsRowResults.length; k++) {
          List results = DL_AnalyticsRowResults[k];
          Map rowMap = results[p];
          List rowMapNums = rowMap['nums'];
          Map numMap = rowMapNums[j];
          bool isRight = numMap['isRight'];
          if (isRight) {
            count++;
          }
        }
        debugPrint('check---$codeString,,count---$count');
        Map codeCountMap = {'code': count.toString(), 'isRight': false};
        codeCountArray.add(codeCountMap);
      }
      Map digitMap = {'title': '', 'nums': codeCountArray};
      DL_CalculatedDrawings.add(digitMap);
    }
    debugPrint('DL_CalculatedDrawings---$DL_CalculatedDrawings');
    DL_getAverageSkipping();
    DL_getMaximumSkipping();
    DL_getMaximumConsecution();
    DL_getChoosingNumber();
  }

  ///计算平均遗漏
  DL_getAverageSkipping() {
    DL_AverageSkipping.clear();
    for (Map element in DL_CalculatedDrawings) {
      List nums = element['nums'];
      List result = [];
      for (int i = 0; i < nums.length; i++) {
        var count;
        if (i <= 4) {
          count = (69 / 5 - 1).round().toString(); //四舍五入后转string
        } else {
          count = (26 / 1 - 1).round().toString();
        }
        Map codeCountMap = {'code': count.toString(), 'isRight': false};
        result.add(codeCountMap);
      }
      Map digitMap = {'title': '', 'nums': result};
      DL_AverageSkipping.add(digitMap);
    }
    debugPrint('DL_AverageSkipping---$DL_AverageSkipping');
  }

  ///计算最大遗漏
  DL_getMaximumSkipping() {
    DL_MaximumSkipping.clear();

    ///遍历每个号码分区
    for (int k = 0; k < DL_CalculatedDrawings.length; k++) {
      Map element = DL_CalculatedDrawings[k];
      List nums = element['nums'];
      List maxCountArray = [];
      for (int i = 0; i < nums.length; i++) {
        int maxCount = 0;
        for (var j = 0; j < DL_AnalyticsRowResults.length; j++) {
          List rowResults = DL_AnalyticsRowResults[j];
          Map rowMap = rowResults[k];
          List rowMapNums = rowMap['nums'];
          //
          Map rowMapNum = rowMapNums[i];
          var rowCode = rowMapNum['code'];
          if (isDigit(rowCode)) {
            ///找出每一列的最大号码
            int digitCode = int.parse(rowCode);
            if (digitCode > maxCount) {
              maxCount = digitCode;
              // print(maxCount);
            }
          }
        }
        maxCountArray.add({'code': maxCount.toString(), 'isRight': false});
      }
      Map digitMap = {'title': '', 'nums': maxCountArray};
      DL_MaximumSkipping.add(digitMap);
    }
    debugPrint('DL_MaximumSkipping---$DL_MaximumSkipping');
  }

  // 使用 int.tryParse 判断字符是否为数字
  bool isDigit(String char) {
    return int.tryParse(char) != null;
  }

  ///计算最大连开
  DL_getMaximumConsecution() {
    DL_MaximumConsecution.clear();

    ///遍历每个号码分区
    for (int k = 0; k < DL_CalculatedDrawings.length; k++) {
      Map element = DL_CalculatedDrawings[k];
      List nums = element['nums'];
      List MaxCountArray = [];

      ///遍历每个分区的每一位号码
      for (int i = 0; i < nums.length; i++) {
        int maxCount = 0; //最大连开次数
        int currentCount = 0; //当前连开次数
        List isRightItems = [];

        //
        for (var j = 0; j < DL_AnalyticsRowResults.length; j++) {
          List rowResults = DL_AnalyticsRowResults[j];
          Map rowMap = rowResults[k];
          List rowMapNums = rowMap['nums'];
          Map rowMapNum = rowMapNums[i];
          bool isRight = rowMapNum['isRight'];
          isRightItems.add(isRight);
        }
        debugPrint('isRightItems---$isRightItems');
        for (bool element in isRightItems) {
          if (element) {
            currentCount++; // 如果是 '1'，则增加当前计数
          } else {
            // 如果不是 '1'，则更新最大计数并重置当前计数
            if (currentCount > maxCount) {
              maxCount = currentCount;
            }
            currentCount = 0; // 重置当前计数
          }
        }
        // 在循环结束后检查一次
        if (currentCount > maxCount) {
          maxCount = currentCount;
        }

        Map codeCountMap = {'code': maxCount.toString(), 'isRight': false};
        MaxCountArray.add(codeCountMap);
      }
      Map digitMap = {'title': '', 'nums': MaxCountArray};
      DL_MaximumConsecution.add(digitMap);
    }
    debugPrint('DL_MaximumConsecution---$DL_MaximumConsecution');
  }

  ///选号栏
  DL_getChoosingNumber() {
    DL_ChooseNumbers.clear();

    ///遍历每个号码分区
    for (List digitData in DL_DigitsDatas) {
      var codeCountArray = [];

      ///遍历每个分区的每一位号码
      for (var element in digitData) {
        String codeString = element['code'];
        Map codeCountMap = {'code': codeString, 'isRight': false};
        codeCountArray.add(codeCountMap);
      }
      DL_ChooseNumbers.add({'title': '', 'nums': codeCountArray});
    }
    debugPrint('KL_ChooseNumbers---$DL_ChooseNumbers');
  }

  ///
  ///
}
